<?php

/**
 * 获取客户端IP地址
 */
function get_client_ip(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR");
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}


/**
 * 获取给定IP的物理地址
 * 
 * @param string $ip
 * @return string
 */
function convert_ip($ip) {
	$return = '';
	if(preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) {
		$iparray = explode('.', $ip);
		if($iparray[0] == 10 || $iparray[0] == 127 || ($iparray[0] == 192 && $iparray[1] == 168) || ($iparray[0] == 172 && ($iparray[1] >= 16 && $iparray[1] <= 31))) {
			$return = '- LAN';
		} elseif($iparray[0] > 255 || $iparray[1] > 255 || $iparray[2] > 255 || $iparray[3] > 255) {
			$return = '- Invalid IP Address';
		} else {
			$tinyipfile = QUICK_ADDONE_PATH.'/libs/misc/tinyipdata.dat';
			$fullipfile = QUICK_ADDONE_PATH.'/libs/misc/wry.dat';
			if(@file_exists($tinyipfile)) {
				$return = convert_ip_tiny($ip, $tinyipfile);
			} elseif(@file_exists($fullipfile)) {
				$return = convert_ip_full($ip, $fullipfile);
			}
		}
	}
	$return = iconv('GBK', 'UTF-8', $return);
	return $return;
}

/**
 * @see convert_ip()
 */
function convert_ip_tiny($ip, $ipdatafile) {
		static $fp = NULL, $offset = array(), $index = NULL;
	
		$ipdot = explode('.', $ip);
		$ip    = pack('N', ip2long($ip));
	
		$ipdot[0] = (int)$ipdot[0];
		$ipdot[1] = (int)$ipdot[1];
	
		if($fp === NULL && $fp = @fopen($ipdatafile, 'rb')) {
			$offset = unpack('Nlen', fread($fp, 4));
			$index  = fread($fp, $offset['len'] - 4);
		} elseif($fp == FALSE) {
			return  '- Invalid IP data file';
		}
	
		$length = $offset['len'] - 1028;
		$start  = unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
	
		for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) {
	
			if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip) {
				$index_offset = unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
				$index_length = unpack('Clen', $index{$start + 7});
				break;
			}
		}
	
		fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
		if($index_length['len']) {
			return '- '.fread($fp, $index_length['len']);
		} else {
			return '- Unknown';
		}
	
}

/**
 * @see convert_ip()
 */
function convert_ip_full($ip, $ipdatafile) {
	if (! $fd = @fopen ( $ipdatafile, 'rb' )) {
		return '- Invalid IP data file';
	}
	
	$ip = explode ( '.', $ip );
	$ipNum = $ip [0] * 16777216 + $ip [1] * 65536 + $ip [2] * 256 + $ip [3];
	
	if (! ($DataBegin = fread ( $fd, 4 )) || ! ($DataEnd = fread ( $fd, 4 )))
		return;
	@$ipbegin = implode ( '', unpack ( 'L', $DataBegin ) );
	if ($ipbegin < 0)
		$ipbegin += pow ( 2, 32 );
	@$ipend = implode ( '', unpack ( 'L', $DataEnd ) );
	if ($ipend < 0)
		$ipend += pow ( 2, 32 );
	$ipAllNum = ($ipend - $ipbegin) / 7 + 1;
	
	$BeginNum = $ip2num = $ip1num = 0;
	$ipAddr1 = $ipAddr2 = '';
	$EndNum = $ipAllNum;
	
	while ( $ip1num > $ipNum || $ip2num < $ipNum ) {
		$Middle = intval ( ($EndNum + $BeginNum) / 2 );
		
		fseek ( $fd, $ipbegin + 7 * $Middle );
		$ipData1 = fread ( $fd, 4 );
		if (strlen ( $ipData1 ) < 4) {
			fclose ( $fd );
			return '- System Error';
		}
		$ip1num = implode ( '', unpack ( 'L', $ipData1 ) );
		if ($ip1num < 0)
			$ip1num += pow ( 2, 32 );
		
		if ($ip1num > $ipNum) {
			$EndNum = $Middle;
			continue;
		}
		
		$DataSeek = fread ( $fd, 3 );
		if (strlen ( $DataSeek ) < 3) {
			fclose ( $fd );
			return '- System Error';
		}
		$DataSeek = implode ( '', unpack ( 'L', $DataSeek . chr ( 0 ) ) );
		fseek ( $fd, $DataSeek );
		$ipData2 = fread ( $fd, 4 );
		if (strlen ( $ipData2 ) < 4) {
			fclose ( $fd );
			return '- System Error';
		}
		$ip2num = implode ( '', unpack ( 'L', $ipData2 ) );
		if ($ip2num < 0)
			$ip2num += pow ( 2, 32 );
		
		if ($ip2num < $ipNum) {
			if ($Middle == $BeginNum) {
				fclose ( $fd );
				return '- Unknown';
			}
			$BeginNum = $Middle;
		}
	}
	
	$ipFlag = fread ( $fd, 1 );
	if ($ipFlag == chr ( 1 )) {
		$ipSeek = fread ( $fd, 3 );
		if (strlen ( $ipSeek ) < 3) {
			fclose ( $fd );
			return '- System Error';
		}
		$ipSeek = implode ( '', unpack ( 'L', $ipSeek . chr ( 0 ) ) );
		fseek ( $fd, $ipSeek );
		$ipFlag = fread ( $fd, 1 );
	}
	
	if ($ipFlag == chr ( 2 )) {
		$AddrSeek = fread ( $fd, 3 );
		if (strlen ( $AddrSeek ) < 3) {
			fclose ( $fd );
			return '- System Error';
		}
		$ipFlag = fread ( $fd, 1 );
		if ($ipFlag == chr ( 2 )) {
			$AddrSeek2 = fread ( $fd, 3 );
			if (strlen ( $AddrSeek2 ) < 3) {
				fclose ( $fd );
				return '- System Error';
			}
			$AddrSeek2 = implode ( '', unpack ( 'L', $AddrSeek2 . chr ( 0 ) ) );
			fseek ( $fd, $AddrSeek2 );
		} else {
			fseek ( $fd, - 1, SEEK_CUR );
		}
		
		while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) )
			$ipAddr2 .= $char;
		
		$AddrSeek = implode ( '', unpack ( 'L', $AddrSeek . chr ( 0 ) ) );
		fseek ( $fd, $AddrSeek );
		
		while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) )
			$ipAddr1 .= $char;
	} else {
		fseek ( $fd, - 1, SEEK_CUR );
		while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) )
			$ipAddr1 .= $char;
		
		$ipFlag = fread ( $fd, 1 );
		if ($ipFlag == chr ( 2 )) {
			$AddrSeek2 = fread ( $fd, 3 );
			if (strlen ( $AddrSeek2 ) < 3) {
				fclose ( $fd );
				return '- System Error';
			}
			$AddrSeek2 = implode ( '', unpack ( 'L', $AddrSeek2 . chr ( 0 ) ) );
			fseek ( $fd, $AddrSeek2 );
		} else {
			fseek ( $fd, - 1, SEEK_CUR );
		}
		while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) )
			$ipAddr2 .= $char;
	}
	fclose ( $fd );
	
	if (preg_match ( '/http/i', $ipAddr2 )) {
		$ipAddr2 = '';
	}
	$ipaddr = "$ipAddr1 $ipAddr2";
	$ipaddr = preg_replace ( '/CZ88\.NET/is', '', $ipaddr );
	$ipaddr = preg_replace ( '/^\s*/is', '', $ipaddr );
	$ipaddr = preg_replace ( '/\s*$/is', '', $ipaddr );
	if (preg_match ( '/http/i', $ipaddr ) || $ipaddr == '') {
		$ipaddr = '- Unknown';
	}
	
	return '- ' . $ipaddr;

}

// 实例化hook
function hook($name,$params=array()) {
    return X($name,$params=array(),'Hook');
}

// 实例化插件
function plugin($name,$params=array()) {
    return X($name,$params=array(),'Plugin');
}

// 实例化服务
function service($name,$params=array()) {
    return X($name,$params=array(),'Service');
}


// 实例化widget
function widget($name,$params=array(),$return=false) {
    return W($name,$params,$return);
}

// 实例化model
function model($name,$params=array()) {
    return X($name,$params=array(),'Model');
}

// 调用接口服务
function X($name,$params=array(),$domain='Service') {
    static $_service = array();
    //if(empty($app))
    $app =  C('DEFAULT_APP');

    if(isset($_service[$domain.'_'.$app.'_'.$name]))
        return $_service[$domain.'_'.$app.'_'.$name];

	$class = $name.$domain;
	if(file_exists(LIB_PATH.$domain.'/'.$class.'.class.php')){
		require_cache(LIB_PATH.$domain.'/'.$class.'.class.php');
	}else{
		require_cache(SITE_PATH.'/core/quick/interface/'.strtolower($domain).'s/'.$class.'.class.php');
	}
	//服务不可用时 记录日志 或 抛出异常
	if(class_exists($class)){
		$obj   =  new $class($params);
		$_service[$domain.'_'.$app.'_'.$name] =  $obj;
		return $obj;
	}else{
		throw_exception(L('_CLASS_NOT_EXIST_').':'.$class);
	}
}

/**
 * 根据access.inc.php检查是否有权访问当前节点(APP_NAME/MODULE_NAME/ACTION_NAME)
 * @return boolean
 */
function canAccess() {
	return true;
	$acl = C('access');
	return $acl[APP_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME] === true
		|| $acl[APP_NAME.'/'.MODULE_NAME.'/*'] === true
		|| $acl[APP_NAME.'/*/*'] === true;
}


//alias_import(array(
	//'Service'		=>	CORE_PATH.'/giftcore/Service.class.php',
	//'Model'			=>	CORE_PATH.'/giftcore/Model.class.php',
	//'Action'		=>	CORE_PATH.'/giftcore/Action.class.php',
	//'View'			=>	CORE_PATH.'/giftcore/View.class.php',
	//'Widget'		=>	CORE_PATH.'/giftcore/Widget.class.php',
	//'Api'		    =>	CORE_PATH.'/giftcore/Api.class.php',
//    )
//);

//输出纯文本
function t($text,$parseBr=false){
	//$text	=	strip_tags($text);
	if(!$parseBr){
		$text	=	str_replace(array("\r","\n","\t"),' ',$text);
	}else{
		$text	=	nl2br($text);
	}
	$text   = stripslashes($text);
	$text	= htmlspecialchars($text, ENT_NOQUOTES,'UTF-8 ');
	
	return $text;
}


/**
 * 对strip_tags函数的扩展, 可以过滤object, param, embed等来自编辑器的标签
 * @param unknown_type $str
 * @param unknown_type $allowable_tags
 */
function real_strip_tags($str, $allowable_tags) {
	$str = stripslashes(htmlspecialchars_decode($str));
	return strip_tags($str, $allowable_tags);
}

//将字符串截断制定长度
function getShort($str,$length=40) {
	$str	=	htmlspecialchars($str);
	$str	=	strip_tags($str);
	$str	=	htmlspecialchars_decode($str);
	$strlenth	=	0;
	$out		=	'';
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/", $str, $match);
	foreach($match[0] as $v){
		preg_match("/[\xe0-\xef][\x80-\xbf]{2}/",$v, $matchs);
		if(!empty($matchs[0])){
			$strlenth	+=	1;
		}elseif(is_numeric($v)){
			$strlenth	+=	0.545;
		}else{
			$strlenth	+=	0.475;
		}

		if($strlenth>$length){
			break;
		}

		$output	.=	$v;
	}
	return $output;
}


/**
 * 通过循环遍历将对象转换为数组
 * 
 * @param object $var
 * @return array
 */
function object_to_array($var) {
	if ( is_object($var) )
		$var = get_object_vars($var);
	
	if ( is_array($var) )
		$var = array_map('object_to_array', $var);
	
	return $var;
}


/**
* 去一个二维数组中的每个数组的固定的键知道的值来形成一个新的一维数组
* @param $pArray 一个二维数组
* @param $pKey 数组的键的名称
* @return 返回新的一维数组
*/
function getSubByKey($pArray, $pKey="", $pCondition=""){
		$result = array();
		foreach($pArray as $temp_array){
				if(is_object($temp_array)){
						$temp_array = (array) $temp_array;
				}
				if((""!=$pCondition && $temp_array[$pCondition[0]]==$pCondition[1]) || ""==$pCondition) {
						$result[] = (""==$pKey) ? $temp_array : isset($temp_array[$pKey]) ? $temp_array[$pKey] : "";
				}
		}
		return $result;
}


/**
 * Format a mySQL string correctly for safe mySQL insert (no mater if magic quotes are on or not)
 */
function escape($str) {
	return mysql_escape_string(stripslashes($str));
}

//province city area
/**
*	获得区域描述
**/
function getAreaDesc($provinceid,$cityid,$areaid,$defaultDesc=''){
		//$pNetwork = M('Area');
		$list = _selectarea($provinceid,$cityid,$areaid);
		if(!$list)return $defaultDesc;
		return $list[$provinceid]['title'].' '.$list[$cityid]['title'].' '. $list[$areaid]['title']; 
}


/**
*	获得区域描述
**/
function assembleAreaIds($provinceid,$cityid,$areaid){
		$result = $provinceid.','.$cityid.','.$areaid;
		return $result;
}


/**
*	查询区域信息。
*	返回：对应数组,通过对应id可获得对应数据
**/
function _selectarea($provinceid,$cityid,$areaid){
		$ifPempty = empty($provinceid);
		$ifCempty = empty($cityid);
		$ifAempty = empty($areaid);
		$where = '';

		//拼装对应的sql语句。
		if(!$ifPempty){
				$where = $where.' area_id='.$provinceid;
		}else{
				return null;
		}
		if(!$ifCempty){
				$where = $where.' or area_id='.$cityid;
				if(!$ifAempty){
						$where = $where.' or area_id='.$areaid;
				}
		}

		$result = D('Area')->where($where)->findall();
		//排序
		foreach ($result as $key => $value){
				$id = $value['area_id'];
				$list[$id]['id']    = $value['area_id'];
				$list[$id]['pid']    = $value['pid'];
				$list[$id]['title']  = $value['title'];
		}
		return $list;
}


/**
*	通用获取分类描述方法。
*	$cateId		类别ID
**/
function getCategoryName($code,$default_value=''){
		if(empty($code))return $default_value;
		$category = M('Dict')->where("code='".$code."'")->find();
		if(empty($category))return $default_value;
		return $category['desc'];
}

/**
*	通用获取分类描述方法。
*	$cateId		类别ID
**/
function getCategoryNameById($id,$default_value=''){
		if(empty($id))return $default_value;
		$category = M('Dict')->where("id=".$id)->find();
		if(empty($category))return $default_value;
		return $category['desc'];
}


/**
*	通用获取分类code方法。
*	$cateId		类别ID
**/
function getCategoryCode($cateId,$default_value=''){
		if(empty($cateId))return $default_value;
		$category = M('Dict')->where('id='.$cateId)->find();
		if(empty($category))return $default_value;
		return $category['code'];
}


/**
*	解析时间，将2011-03-03 12:22:22格式的时间转换成毫秒数
**/
function paramDate( $date ) {
    $date_list = explode( ' ',$date );
    list( $year,$month,$day ) = explode( '-',$date_list[0] );
    if(!empty($date_list[1]))list( $hour,$minute,$second ) = explode( ':',$date_list[1] );
   	return mktime( $hour,$minute,$second,$month,$day,$year );
}

/**
*	将毫秒数转换成格式化的日期
*	'Y-m-d'  Y-m-d h:i:s  Y-m-d H:i:s
**/
function paramMillisecond2Date($millisecond,$format='Y-m-d',$default_value=''){
		if(empty($millisecond))return $default_value;
		$str = date( $format,$millisecond);
		return $str;
}

/**
 * 解析毫秒，返回年月日时分秒数组。
 * 返回格式：$result['year'],$result['month'],$result['day'],$result['hour'],$result['minute'],$result['second']
 * @param string $millisecond
 */
function paramMillisecond2Ary($millisecond){
	if(empty($millisecond))return null;
	$date = date( 'Y-m-d H:i:s',$millisecond);
	$date_list = explode( ' ',$date );
    list( $result['year'],$result['month'],$result['day']) = explode( '-',$date_list[0] );
    if(!empty($date_list[1]))list( $result['hour'],$result['minute'],$result['second'] ) = explode( ':',$date_list[1] );
    return $result;
}

/**
*	获得上传文件完整路径
**/
function getAttachUrl($savepath) {
	return '/data/uploads/'.$savepath;
}

/**
*	调用图片生成工具thumb.php的封装方法．
**/
function getPhotoFromThumb($photopath,$w,$h,$isrelpath=true) {
	if($isrelpath)$fullpath = getAttachUrl($photopath);
	else $fullpath=$photopath;
	//return "/thumb.php?w=".$w."&h=".$h."&url=http://".$_SERVER['HTTP_HOST'].$fullpath;
	return "/thumb.php?w=".$w."&h=".$h."&url=.".$fullpath;
}


//检查Email地址是否合法
function isValidEmail($email) {
	return preg_match("/[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+$/i", $email) !== 0;
}
	
/**
 * 检查手机号码是否合法
 * 
 * @return boolean
 */
function isValidMobile($mobilephone) {
		//$mobilephone1=trim($mobilephone);   
		//手机号码的正则验证   
					 ///^13[0-9]{1}[0-9]{8}$|15[01589]{1}[0-9]{8}$|189[0-9]{8}$|186[0-9]{8}$/
		if(preg_match(C('MOBILE_CHECK_EXP'),$mobilephone)){   
		     //验证通过   
		     return true;
		}else{   
		     //手机号码格式不对   
		     return false;  
		}  
}

/**
 * 将数组转换成字符串，目前主要用于日志打印数组。
 * @param unknown_type $ary
 */
function parseAry2Str($ary){
	$result = '';
	foreach($ary as $key=>$val){
		if(is_array($val)){
			$result = $result."[{$key}]->".parseAry2Str($val)."\n\r";
		}else{
			$result = $result."[{$key}]={$val} ";
		}
	}
	return $result;
}


/**
 * 从数组中(一维、二维均可)，依据key获得新数组。
 * @param 二位数组 $ary
 * @param array $keys
 * @param array $newkey	表示将数组中的key对应的值，与新key对应（原key=value保留）$newkey=array('oldkey'=>'newkey')
 */
function getNewFromArray($ary,$keys,$newkey=null){
	$result = '';
	foreach($ary as $key=>$val){
		if(is_array($val)){
			$result[$key]=getNewFromArray($val,$keys,$newkey);
		}else{
			if(in_array($key,$keys)){
				$result[$key]=$val;
				if(!empty($newkey)){
					foreach($newkey as $key1=>$val1){
						//echo $key."|".$key1;
						if($key==$key1)$result[$val1]=$val;
					}
				}
			}
			
		}
	}
	return $result;
}


/**格式化金额为00.00格式**/
function formatMoney($money){
	return sprintf("%01.2f",$money).' 元';
}

function payStateDesc($state){
	if($state=='pay')return '已支付';
	return '未支付';
}


/**
 * 获取用户头像
 * 
 * @param int    $uid  用户ID
 * @param string $size 头像大小 m:中图 | s:小图 | 其他:大图
 * @return string 头像的URL地址
 */
function getUserFace($uid,$size){
	$size = ($size)?$size:'m';
	if($size=='m'){
		$type = 'middle.jpg';
	}elseif ($size=='s'){
		$type = 'small.jpg';
	}else{
		$type = 'big.jpg';
	}
	$userface = SITE_PATH.'/data/uploads/avatar/'.$uid.'/'.$type;
	if(is_file($userface)){
		return SITE_URL."/data/uploads/avatar/$uid/$type";
	}else{
		return SITE_URL."/Public/Images/global/user_pic.gif";
	}
}

/**
 * 获取礼券状态，
 * @param array $couponinfo		礼券数据数组
 * @param String $rtn_type		返回什么数据		desc=返回状态描述字符串	ary=否则返回数组
 */
function getCouponStatus($couponinfo,$rtn_type='desc'){
	if(empty($couponinfo['checker_id'])||$couponinfo['checker_id']==0){
		$result['code']='unused';
		$result['desc']='未使用';
	}
	if(!empty($couponinfo['checker_id'])&&$couponinfo['checker_id']>0){
		$result['code']='used';
		$result['desc']='已使用';
	}
	if($result['code']=='unused'&&time()>$couponinfo['expired_date']){
		$result['code']='expired';
		$result['desc']='已过期';
	}
	if($rtn_type=='desc')return $result['desc'];
	return $result;
}

function formatSendTargetTime($target_date,$target_hour){
	return paramMillisecond2Date($target_date)
							.'&nbsp;-&nbsp;'.($target_hour==0?'即刻':$target_hour.'时').'&nbsp;发送';
}
/**
 * 获取发送状态，及发送预定时间。相关信息。
 * @param unknown_type $couponInfo
 * @param unknown_type $is_pay
 */
function getSendStatus($couponInfo){
	$result['target_time']=formatSendTargetTime($couponInfo['target_date'],$couponInfo['target_hour']);
	
	if($couponInfo['is_active']=='N'){
		$result['code']='unpay';
		$result['desc']='未付款，无法进行发送！';
		$result['icon']="icon_send_fail.gif";
		return $result;
	}
	
	if($couponInfo['is_send']=='Y'){
		$result['code']='sended';
		$result['desc']=K('SP_COUPON_NM').'已发送！发送时间：'.paramMillisecond2Date($couponInfo['sendtime'],'Y-m-d H:i');
		$result['icon']="icon_send_done.gif";
		return $result;
	}
	
	if($couponInfo['is_send']=='E'){
		$result['code']='error';
		$result['desc']=K('SP_COUPON_NM').'已失败！发送时间：'.paramMillisecond2Date($couponInfo['sendtime'],'Y-m-d H:i');
		$result['icon']="icon_send_error.gif";
		return $result;
	}
	
	//判断发送时间，与当前时间。
	if( ( $couponInfo['target_date'] + ( intval($couponInfo['target_hour'])*60*60 ) )<time()){
		$result['code']='sending';
		$result['desc']='正在发送中...';
		$result['icon']="icon_send_doing.gif";
		return $result;
	}
	
	$result['code']='waiting';
	$result['desc']='发送时间未到！'.K('SP_COUPON_NM').'等待发送！';
	$result['icon']="icon_send_waiting.gif";
	
	return $result;
}

function getMmsBg($shelfid){
	$relpath = service('SmsImg')->getMmsBg($shelfid);
	return $relpath;
}

function getChanelDesc($chanel){
	$result = "";
	$ary_chanel = explode(',',$chanel);
	if( in_array('sms', $ary_chanel ) ){	
		$result = "短信";
	}	
	if( in_array('mms', $ary_chanel ) ){	
		if(empty($result))$result = "彩信";
		else $result = $result."、彩信";
	}	
	if( in_array('email', $ary_chanel ) ){	
		if(empty($result))$result = "邮件";
		else $result = $result."、邮件";
	}			
	return $result;
}

function ifCouponUsed($checker_id,$check_time){
	if(!empty($checker_id)||$check_time>0){
		return true;
	}
	return false;
}



/**
*	通用获取商户名称方法。
*	$cateId		商户ID
**/
function getParnterTitle($partId,$default_value=''){
		if(empty($partId))return $default_value;
		$partner = M('Partner')->where("id=".$partId)->find();
		if(empty($partner))return $default_value;
		return $partner['title'];
}


/**
 * 读取页面资源文件（类似于国际化）。通过key读取对应的value显示在页面上。
 */
function K($key){
	$configTpltfpath = K_CONFIG_PATH.'config_propoties.php';
	$ary_config = (include $configTpltfpath);
	return $ary_config[$key];
}


/**
 * 将数据转换为map.js所需的json格式数据。
 */
function format2MapData($stores){
	//echo "format2MapData";
	$result = null;
	foreach($stores as $key=>$vo){
		//dump($vo);
		$store = null;
		$store['phone']='';
		if($vo['phone']>0)$store['phone']=$vo['phone'];
		if($vo['mobile']>0){
			if(!empty($store['phone']))$store['phone']=$store['phone'].' / '.$vo['mobile'];
			else $store['phone']=$vo['mobile'];
		}
		
		$store['address']=$vo['address'];
		$store['store_logo']=getPhotoFromThumb($vo['brand_icon'],80,80);
		$store['store_id']=$vo['id'];//地图上标点的唯一标示
		if($vo['parent_id']==0)$store['brand_id']=$vo['id'];
		else $store['brand_id']=$vo['parent_id'];
		$store['store_name']=$vo['title'];
		$latlng = explode(',',$vo['location']);
		$store['geolong']=$latlng[1];
		$store['geolat']=$latlng[0];
		$store['brief']=$vo['brief'];
		$result[] = $store;
	}
	//dump($result);
	return $result;
}


/**
 * 返回礼物兑换方式的描述
 */
function getGoodsGetTypeDesc($type_){
	if($type_=='delivery'){
		return "快递送货";
	}
	if($type_=='all'){
		return "快递送货、到店自取";
	}
	return "到店自取";
}


/**
 * 获得短信发送模板
 */
function getMMSContentTemplet(){
	$configTpltfpath = K_CONFIG_PATH.'config_templet.php';
	$ary_templet = (include $configTpltfpath);
	return $ary_templet;
}


function getMMSExtInfo($goods_get_type,$partner_phone,$partner_mobile){
	//echo $goods_get_type."-".$partner_phone."-".$partner_mobile."<br>";
	$_goods_ext_info = "";
	if($goods_get_type=='delivery'||$goods_get_type=='all'){
		if(!empty($partner_phone)&&$partner_phone>0){
			$_goods_ext_info = $partner_phone;
		}
		if(!empty($partner_mobile)&&$partner_mobile>0){
			if(empty($_goods_ext_info))$_goods_ext_info = $partner_mobile;
			else $_goods_ext_info = $_goods_ext_info.",".$partner_mobile;
		}
		if(empty($_goods_ext_info)){
			$_goods_ext_info = "登录小心意查看商家送货电话";
		}else{
			$_goods_ext_info = "拨打".$_goods_ext_info."告知商家快递地址";
		}
	}
	return $_goods_ext_info;
}


function assembleMMSData(&$tplt_data){
	//dump($tplt_data);
	if(empty($tplt_data['{goods_ext_info}'])||$tplt_data['{goods_ext_info}']==''){
		$tplt_data['{partner_title}'] = "请在".$tplt_data['{partner_title}']."（北京）兑换";
	}else{
		$tplt_data['{partner_title}'] = $tplt_data['{goods_ext_info}']."（".$tplt_data['{partner_title}']."）";
		$tplt_data['{goods_ext_info}'] = "";
	}
	//dump($tplt_data);
	return $tplt_data;
}


function exchangeTimeDesc($extime){
	if($extime==null||empty($extime)){
		return "心意券需在购买日起".C('COUPON_EXPIRED_DATE')."天内兑换！";
	}else{
		$time1 = paramMillisecond2Date($extime,$format='Y年m月d日',"有效期未设置");
		return "心意券需在".$time1."前兑换！";
	}
}

/**
 * 计算返利金额
 * @param unknown_type $total			订单总金额。支付记录中金额累加。
 * @param unknown_type $cashpayed		现金支付金额。
 * @param unknown_type $rebate			返利值，与$rebate_model对应。
 * @param unknown_type $rebate_model	返利方式取值dict中的rebate下的数据。
 */
function countRebateValue($total,$cashpayed,$rebate,$rebate_model){
	//$rebatedict = service('Dict')->getAllDirectSubDicts('rebate','code');
	$rebatedict = array('rebate_percent','rebate_money');
	if($total<=0||$rebate<=0||$cashpayed<=0||!in_array($rebate_model,$rebatedict)){
		return '0';
	}
	//$count_base = $total-$cashpayed;
	if($total<$cashpayed){
		$cashpayed=$total;
	}
	
	if($rebate_model=='rebate_percent'){
		return $cashpayed*$rebate/100;
	}
	
	if($rebate_model=='rebate_money'){
		return $cashpayed*$rebate/$total;
	}
}

?>